package com.cskt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cskt.common.constants.ErrorCodeEnum;
import com.cskt.common.constants.SystemConstants;
import com.cskt.common.exception.ServiceException;
import com.cskt.common.condition.UserRegisterCondition;
import com.cskt.service.MailService;
import com.cskt.service.SmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.MailSender;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cskt.entity.User;
import com.cskt.mapper.UserMapper;
import com.cskt.service.UserService;
import  com.cskt.util.MD5.MD5;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private static final Logger log =
            LoggerFactory.getLogger(UserServiceImpl.class);
    //用户注册码的前缀
    private static final String ACTIVE_CODE_PRE = "active";

    //是否发送邮件的开关
    @Value(value = "${email.send.enable}")
    private boolean enableSendEmail;
    //是否发送短信
    @Value(value = "${sms.send.enable}")
    private boolean enableSendSms;
    @Resource
    private SmsService smsService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private  MailService mailService;


    @Override
    public boolean userRegister(UserRegisterCondition condition,String
            registerType) {

            LambdaQueryWrapper<User> eq = new QueryWrapper<User>().lambda().eq(User::getUserCode, condition.getUserCode());
            User user = this.getOne(eq);
            if (user != null) {
                //用户已经存在，直接抛出异常
                log.warn("账号已经存在");
                throw new
                        ServiceException(ErrorCodeEnum.AUTH_USER_ALREADY_EXISTS);

            }
            //处理数据并且完成类型转换
            condition.setUserPassword(MD5.getMd5(condition.getUserPassword(),32));
            User registeuser=new User();
            BeanUtils.copyProperties(condition, registeuser);
            //指定用户类型，默认为系统自注册用户
            registeuser.setUserType(SystemConstants.UserType.REGISTRATION);
            //执行用户新增
            this.save(registeuser);
            //根据不同的注册类型，执行不同的验证码相关生成策略
           switch (registerType){
               case "mail":
                   //生成激活码
                   String activeCode = MD5.getMd5(String.valueOf(System.currentTimeMillis()), 32);
                   log.info("激活码：{}",activeCode);
                   //发送激活码邮件
                   if(enableSendEmail){
                       mailService.sendActivationMail(registeuser.getUserCode(), activeCode);
                   }
                   //存入redis并且设置时长为38分钟
                   stringRedisTemplate.opsForValue().set(ACTIVE_CODE_PRE+condition.getUserCode(),activeCode,30, TimeUnit.MINUTES);
                break;
               case "phone":
                   //生成验证码
                   int randomCode = MD5.getRandomCode();
                            //将手机验证码存入到redis并且设置过期时间为五分钟
                            stringRedisTemplate.opsForValue().set(ACTIVE_CODE_PRE + condition.getUserCode(),String.valueOf(randomCode),5,TimeUnit.MINUTES);
                            log.info("短信验证码：{}",randomCode);
                    //与上面的邮件是否发送同理，短信发一条就是一条的钱
                   if (enableSendSms) {
                //发送验证码
                       smsService.sendMessage(condition.getUserCode(),String.valueOf(randomCode));
                   }
                   break;
               default:
                   break;

           }


        System.out.println("到这里来了");
        return true;
    }

    @Override
    public boolean validatePhone(String phoneNum, String code) {
        String  key=ACTIVE_CODE_PRE+phoneNum;
        //从redis中取出验证码
        String value = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.hasLength(value)&&value.equals(code)) {
            //验证通过
            LambdaQueryWrapper<User> queryWrapper = new QueryWrapper<User>().lambda().eq(User::getUserCode, phoneNum);
            User user = this.getOne(queryWrapper);
            //更新状态为已激活
            user.setActivated(SystemConstants.UserActiveStatus.IS_ACTIVE);
            //更新第三方id为自己的id
            user.setFlatId(user.getId());
            //执行更新
            return this.updateById(user);
        }
        return false;
    }

    @Override
    public User findUserByUserCode(String userCode) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_code", userCode);
        return this.getOne(userQueryWrapper);

    }

   /*
    public void insertUserByPhone(User user) {
        this.save(user);
//生成验证码
        int randomCode = MD5.getRandomCode();
//发送验证码
        smsService.sendMessage(user.getUserCode(),"1");
//存入到redis
        stringRedisTemplate.opsForValue().set("activition:" + user.getUserCode(),
                String.valueOf(randomCode), 5, TimeUnit.MINUTES);

    }*/
}
